import { addCourseCommentApi, getCourseCommentApi } from '@/api/api';
import { HeartOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Avatar, Button, Form, Input } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Comment } from '@/api/api';
import dayjs from 'dayjs';
import useApp from 'antd/es/app/useApp';

interface ReviewProps {
  id: string; // 课程id
}

interface CommentTree extends Comment {
  children: Comment[];
}

// 用户评论组件
const Review = ({ id }: ReviewProps) => {
  const app = useApp();
  const [mainForm] = Form.useForm(); // 主评论表单
  const [replyForm] = Form.useForm(); // 回复评论表单
  const [commentList, setCommentList] = useState<Comment[]>([]);
  // 当前回复的评论
  const [replyingTo, setReplyingTo] = useState<Comment | null>(null);

  // 将评论列表转换为扁平化的两级结构
  // 无论评论嵌套多深，都只会有父评论和直接子评论两级
  // 并按照时间从新到旧排序
  const commentTree = useMemo(() => {
    // 创建一个映射来存储评论ID到评论对象的映射
    const commentMap = new Map<string, CommentTree>();

    // 初始化所有评论，先把所有评论转为带children的格式
    commentList.forEach((comment) => {
      commentMap.set(comment.id, {
        ...comment,
        children: [],
      });
    });

    // 分为根评论(parentId为null)和子评论
    const rootComments: CommentTree[] = [];
    const childComments: Comment[] = [];

    // 将评论分类为根评论和子评论
    commentList.forEach((comment) => {
      if (comment.parent_id === null) {
        rootComments.push(commentMap.get(comment.id) as CommentTree);
      } else {
        childComments.push(comment);
      }
    });

    // 处理所有子评论，将它们都作为根评论的直接子评论
    childComments.forEach((comment) => {
      // 找到该评论的直接父评论
      let parentComment = commentMap.get(comment.parent_id || '');

      // 如果直接父评论不是根评论，我们需要沿着树向上寻找根评论
      while (parentComment && parentComment.parent_id !== null) {
        parentComment = commentMap.get(parentComment.parent_id || '');
      }

      // 如果找到了根评论，将子评论添加到根评论的children中
      if (parentComment) {
        parentComment.children.push(comment);
      }
    });

    // 根评论按照创建时间从新到旧排序
    rootComments.sort((a, b) => {
      return dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf();
    });

    // 对每个根评论的子评论也按照创建时间从新到旧排序
    rootComments.forEach((rootComment) => {
      rootComment.children.sort((a, b) => {
        return dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf();
      });
    });

    return rootComments;
  }, [commentList]);

  // 获取课程评论
  const getCourseComment = useCallback(async () => {
    const res = await getCourseCommentApi(id as any);
    setCommentList(res.data);
  }, [id]);

  // 处理回复按钮点击
  const handleReply = async (comment: Comment) => {
    console.log('comment', comment);

    setReplyingTo(comment);
    replyForm.resetFields();
  };

  // 取消回复
  const cancelReply = () => {
    setReplyingTo(null);
  };

  // 查找评论的原始发布者（用于显示回复谁）
  const findReplyTarget = (comment: Comment): string => {
    if (!comment.parent_id) return '';

    // 在原始评论列表中查找父评论作者
    const parentComment = commentList.find((c) => c.id === comment.parent_id);
    if (parentComment) {
      return parentComment.user_info.username;
    }
    return '';
  };

  // 处理评论提交
  const handleSubmitComment = async () => {
    await mainForm.validateFields();
    const values = mainForm.getFieldsValue();
    const res = await addCourseCommentApi({
      content: values.content,
      course_id: id,
      parent_id: null,
      root_id: null,
    });
    if (res.code === 200) {
      app.message.success('评论发表成功');
      getCourseComment();
      // 这里添加评论提交逻辑
      mainForm.resetFields();
    }
  };

  // 处理回复提交
  const handleSubmitReply = async () => {
    if (!replyingTo) return;
    replyForm.validateFields();
    const values = replyForm.getFieldsValue();

    const res = await addCourseCommentApi({
      content: values.content,
      course_id: id,
      parent_id: replyingTo.id,
      root_id: replyingTo.root_id,
    });
    if (res.code === 200) {
      app.message.success('回复发表成功');
      getCourseComment();
    }
    // 这里添加回复提交逻辑
    replyForm.resetFields();

    setReplyingTo(null);
  };

  useEffect(() => {
    getCourseComment();
  }, [getCourseComment]);

  return (
    <div className="w-full">
      <div className="text-[24px] font-bold">用户评论：</div>
      {/* 主评论输入框 */}
      <div className="w-full pt-[10px]">
        <Form
          form={mainForm}
          layout="vertical"
        >
          <Form.Item
            label="欢迎您对本课进行评论:"
            name="content"
            rules={[{ required: true, message: '请输入评论内容' }]}
          >
            <Input.TextArea
              placeholder="善语结善缘，恶语伤人心，请文明评论"
              rows={4}
              maxLength={100}
              showCount
            />
          </Form.Item>
        </Form>
        <div className="flex justify-end">
          <Button
            type="primary"
            onClick={handleSubmitComment}
          >
            发表
          </Button>
        </div>
      </div>
      <div className="w-full h-[1px] my-[10px] bg-[#ccc]"></div>

      {/* 评论列表 */}
      <div className="space-y-6">
        {commentTree.length > 0 ? (
          commentTree.map((comment) => (
            <div
              key={comment.id}
              className="comment-thread"
            >
              {/* 父评论 */}
              <div className="flex mb-4">
                {/* 评论头像 */}
                <div className="w-[60px] h-[40px] px-[10px]">
                  <Avatar
                    style={{ width: '40px', height: '40px' }}
                    src={comment.user_info.avatar}
                  />
                </div>
                {/* 评论内容 */}
                <div className="flex flex-col gap-2 flex-1 px-[10px]">
                  {/* 评论者昵称 */}
                  <div className="h-[40px] flex items-center">
                    <span className="text-[16px] font-bold">{comment.user_info.username}</span>
                  </div>
                  {/* 评论内容 */}
                  <div>
                    <span>{comment.content}</span>
                  </div>
                  {/* 评论时间 */}
                  <div className="text-[14px] text-[#ccc] flex items-center gap-2 justify-between">
                    <div>{dayjs(comment.created_at).format('YYYY-MM-DD HH:mm:ss')}</div>
                    <div className="text-[14px] text-[#ccc] flex items-center gap-4">
                      <span
                        className="cursor-pointer hover:text-[#7D33FF]"
                        onClick={() => handleReply(comment)}
                      >
                        回复
                      </span>
                      <span className="cursor-pointer hover:text-[red]">
                        <HeartOutlined />
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 回复输入框 - 仅在当前评论被选中时显示 */}
              {replyingTo && (replyingTo.root_id == comment.id || replyingTo.id == comment.id) && (
                <div
                  className="ml-[60px] mb-4"
                  id={`reply-to-${comment.id}`}
                >
                  <Form
                    form={replyForm}
                    layout="vertical"
                    className="bg-gray-50 p-3 rounded-md border border-gray-100"
                  >
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm text-gray-600">
                        回复
                        <span className="text-blue-500 font-medium">
                          @{replyingTo.user_info.username}
                        </span>
                      </span>
                      <Button
                        type="text"
                        icon={<CloseCircleOutlined />}
                        size="small"
                        onClick={cancelReply}
                        className="text-gray-400 hover:text-gray-600"
                      />
                    </div>
                    <Form.Item
                      name="content"
                      rules={[{ required: true, message: '请输入回复内容' }]}
                      className="mb-2"
                    >
                      <Input.TextArea
                        placeholder="请输入您的回复内容"
                        rows={2}
                        maxLength={100}
                        showCount
                      />
                    </Form.Item>
                    <div className="flex justify-end">
                      <Button
                        type="primary"
                        size="small"
                        onClick={handleSubmitReply}
                      >
                        发表回复
                      </Button>
                    </div>
                  </Form>
                </div>
              )}

              {/* 子评论列表 */}
              {comment.children.length > 0 && (
                <div className="ml-[60px] border-l-2 border-gray-100 pl-4 space-y-4">
                  {comment.children.map((child) => (
                    <div
                      key={child.id}
                      className="flex mt-2"
                    >
                      {/* 子评论头像 */}
                      <div className="w-[50px] h-[40px] px-[5px]">
                        <Avatar
                          style={{ width: '32px', height: '32px' }}
                          src={child.user_info.avatar}
                        />
                      </div>
                      {/* 子评论内容 */}
                      <div className="flex flex-col gap-1 flex-1 px-[5px]">
                        {/* 评论者昵称 */}
                        <div className="h-[30px] flex items-center">
                          <span className="text-[14px] font-bold">{child.user_info.username}</span>
                        </div>
                        {/* 评论内容 - 显示回复对象 */}
                        <div>
                          {findReplyTarget(child) && (
                            <span className="text-blue-500 mr-1">@{findReplyTarget(child)} </span>
                          )}
                          <span>{child.content}</span>
                        </div>
                        {/* 评论时间 */}
                        <div className="text-[12px] text-[#ccc] flex items-center gap-2 justify-between">
                          <div>{dayjs(child.created_at).format('YYYY-MM-DD HH:mm:ss')}</div>
                          <div className="text-[12px] text-[#ccc] flex items-center gap-4">
                            <span
                              className="cursor-pointer hover:text-[#7D33FF]"
                              onClick={() => handleReply(child)}
                            >
                              回复
                            </span>
                            <span className="cursor-pointer hover:text-[red]">
                              <HeartOutlined />
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* 回复输入框 - 当回复子评论但显示在父评论下方 */}
              {replyingTo && replyingTo.parent_id === comment.id && (
                <div
                  className="ml-[60px] mb-4"
                  id={`reply-to-${replyingTo.id}`}
                >
                  <Form
                    form={replyForm}
                    layout="vertical"
                    className="bg-gray-50 p-3 rounded-md border border-gray-100"
                  >
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm text-gray-600">
                        回复
                        <span className="text-blue-500 font-medium">
                          @{replyingTo.user_info.username}
                        </span>
                      </span>
                      <Button
                        type="text"
                        icon={<CloseCircleOutlined />}
                        size="small"
                        onClick={cancelReply}
                        className="text-gray-400 hover:text-gray-600"
                      />
                    </div>
                    <Form.Item
                      name="content"
                      rules={[{ required: true, message: '请输入回复内容' }]}
                      className="mb-2"
                    >
                      <Input.TextArea
                        placeholder="请输入您的回复内容"
                        rows={2}
                        maxLength={100}
                        showCount
                      />
                    </Form.Item>
                    <div className="flex justify-end">
                      <Button
                        type="primary"
                        size="small"
                        onClick={handleSubmitReply}
                      >
                        发表回复
                      </Button>
                    </div>
                  </Form>
                </div>
              )}
            </div>
          ))
        ) : (
          <div className="text-center text-[16px] mt-[20px] text-[#ccc]">
            暂无评论,快来抢沙发吧!
          </div>
        )}
      </div>
    </div>
  );
};

export default Review;
